/*
 * @Author: 张小平
 * @Date:   2025-05-01 
 * @Email:  qqshuqian@163.com 
 * @Copyright © 2024 aseyun. All rights reserved.
 */
import {
  validatenull
} from '@/framework-core/utils/validate';
import website from '@/framework-core/config/website'

const keyName = website.key + '-';
/**
 * 存储localStorage
 */
export const setStore = (params = {}) => {
  let {
    name,
    content,
    type,
  } = params;
  name = keyName + name;

  // 处理 Map 类型转换
  let isMap = content instanceof Map;
  let serializableContent = isMap ? Array.from(content.entries()) : content;

  let obj = {
    dataType: typeof content,
    content: serializableContent,  // 使用转换后的数据
    type: type,
    datetime: Date.now(),
    _isMap: isMap  // 添加类型标识
  };

  if (type) {
    window.sessionStorage.setItem(name, JSON.stringify(obj));
  } else {
    window.localStorage.setItem(name, JSON.stringify(obj));
  }
}

/**
 * 获取localStorage
 */
export const getStore = (params = {}) => {
  let {
    name,
    debug
  } = params;
  name = keyName + name;
  let obj = {};
  let content;

  // 优先从 sessionStorage 读取
  obj = window.sessionStorage.getItem(name);
  if (validatenull(obj)) obj = window.localStorage.getItem(name);
  if (validatenull(obj)) return;

  try {
    obj = JSON.parse(obj);
  } catch {
    return obj;  // 解析失败则返回原始值
  }

  if (debug) {
    return obj;  // 调试模式返回完整对象
  }

  // 增加 Map 类型的恢复处理
  if (obj._isMap) {
    return new Map(obj.content);  // 将二维数组转回 Map
  }
  // 处理基本数据类型
  if (obj.dataType === 'string') {
    content = obj.content;
  } else if (obj.dataType === 'number') {
    content = Number(obj.content);
  } else if (obj.dataType === 'boolean') {
    content = JSON.parse(obj.content);  // 安全转换布尔值
  } else if (obj.dataType === 'object') {
    content = obj.content;  // 普通对象直接返回
  }

  return content;
}
/**
 * 删除localStorage
 */
export const removeStore = (params = {}) => {
  let {
    name,
    type
  } = params;
  name = keyName + name
  if (type) {
    window.sessionStorage.removeItem(name);
  } else {
    window.localStorage.removeItem(name);
  }

}

/**
 * 获取全部localStorage
 */
export const getAllStore = (params = {}) => {
  let list = [];
  let {
    type
  } = params;
  if (type) {
    for (let i = 0; i <= window.sessionStorage.length; i++) {
      list.push({
        name: window.sessionStorage.key(i),
        content: getStore({
          name: window.sessionStorage.key(i),
          type: 'session'
        })
      })
    }
  } else {
    for (let i = 0; i <= window.localStorage.length; i++) {
      list.push({
        name: window.localStorage.key(i),
        content: getStore({
          name: window.localStorage.key(i),
        })
      })

    }
  }
  return list;

}

/**
 * 清空全部localStorage
 */
export const clearStore = (params = {}) => {
  let { type } = params;
  if (type) {
    window.sessionStorage.clear();
  } else {
    window.localStorage.clear()
  }

}
